/**
 * Copyright (c) 2004-2015 All Rights Reserved.
 */
package com.zbest.common.lang.util;

import java.awt.image.BufferedImage;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.Date;
import java.util.Hashtable;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.google.zxing.BarcodeFormat;
import com.google.zxing.EncodeHintType;
import com.google.zxing.MultiFormatWriter;
import com.google.zxing.client.j2se.MatrixToImageWriter;
import com.google.zxing.common.BitMatrix;

/**
 * @author czhou3306@gmail.com
 * @version $Id: QrcodeUtil.java, v0.1 2015年11月26日 下午1:42:28 czhou3306@gmail.com Exp $
 */
public class QrcodeUtil {

    private static final Logger logger = LoggerFactory.getLogger(QrcodeUtil.class);

    public void genQrcodeToFile(String url, String resultPath) {

        try {
            String yyyymmdd = CoreDateUtils.yyyymmdd(new Date());
            String fileName = CoreSystemUtils.objectId() + ".png";

            int width = 180;
            int height = 180;

            Hashtable hints = new Hashtable();
            hints.put(EncodeHintType.CHARACTER_SET, "utf-8");

            BitMatrix bitMatrix = new MultiFormatWriter().encode(url, BarcodeFormat.QR_CODE, width,
                height, hints);
            Path path = Paths.get(resultPath);

            MatrixToImageWriter.writeToPath(bitMatrix, "png", path);
        } catch (Exception e) {
            logger.error("生成二维码异常url=" + url, e);
        }
    }

    public static BufferedImage genQrcodeToBufferedImage(String url) {

        try {
            int width = 180;
            int height = 180;

            Hashtable hints = new Hashtable();
            hints.put(EncodeHintType.CHARACTER_SET, "utf-8");

            BitMatrix bitMatrix = new MultiFormatWriter().encode(url, BarcodeFormat.QR_CODE, width,
                height, hints);

            return MatrixToImageWriter.toBufferedImage(bitMatrix);

        } catch (Exception e) {
            logger.error("生成二维码异常url=" + url, e);
            return null;
        }
    }

}
